package org.bjou

import org.springframework.dao.DataIntegrityViolationException

import java.util.Locale
import java.text.*
import org.apache.shiro.web.util.SavedRequest
import org.apache.shiro.web.util.WebUtils
class JobController {

    static allowedMethods = [update: "POST",saveApply:"POST"]
    
    def choose()
    {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [jobInstanceList: Job.list(params), jobInstanceTotal: Job.count()]
    }

    def apply()
    {
        def  userBaseinfoIntance = UserBaseinfo.findByUser(session.user)
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        
        println "currentTerm:"+ currentTerm
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
        if (params.currentTerm==null) params.currentTerm = currentTerm
        
          
        def cel = {
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
               
            }
            
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            
            if(params.departmentId){  
                eq("department.id", params.departmentId.toLong())  
            }
             
            
            
        }  
        def jobList = Job.createCriteria().list(params,cel) 
        def totalRows = Job.createCriteria().list(cel).size()
        if(!userBaseinfoIntance?.teacherFlag)
        {
            flash.message="请先完善教育简历"
        }
        
        [jobInstanceList: jobList, jobInstanceTotal: totalRows, userBaseinfoIntance: userBaseinfoIntance]
    }
    
    
    def saveApply() {
         
        def userbaseinfo_id  = session.userbaseinfo?.id
        def userBaseinfoInstance = UserBaseinfo.findById(userbaseinfo_id)
        def i=0
            
       println params
        if(userBaseinfoInstance)
        {
            params.list('applyJob').each {
                println "ch:"+ it
                def jobInstance = Job.findById(it)
                userBaseinfoInstance.addToJobs(jobInstance)
                userBaseinfoInstance.save()
                i++
            }
            flash.message="成功申请了"+i+"个职位"
            redirect(action: "applyList")
        }
        else
        {
            flash.message="请先补充个人信息"
            redirect(action: "apply")
        }
        
       
       
        
    }
    
    
    def deleteApply() {
        def userbaseinfo_id  = session.userbaseinfo?.id
        def userBaseinfoInstance = UserBaseinfo.findById(userbaseinfo_id)
        if(userBaseinfoInstance)
        {
            def jobInstance = Job.get(params.id)
            userBaseinfoInstance.removeFromJobs(jobInstance)
            userBaseinfoInstance.save(flush: true)
            flash.message="成功删除了职位"
            redirect(action: "applyList")
        }
       
        
        
      
    }
    
    def applyList()
    {
       
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
        
        def userbaseinfoId  = session.userbaseinfo?.id
          
        def cel = {
            sqlRestriction ("id in(select job_id from user_baseinfo_job where user_baseinfo_jobs_id ="+userbaseinfoId+")"  )
        }  
        
        def jobList = Job.createCriteria().list(params,cel)
        
        
        
        [jobInstanceList: jobList, jobInstanceTotal: jobList.totalCount]
    }
    
    
    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [jobInstanceList: Job.list(params), jobInstanceTotal: Job.count()]
    }

    def create() {
        print params
        def job = new Job(params)
        
        
        [jobInstance: job]
    }
    
    

    def save() {
        println params
        def jobInstance = new Job(params)
        jobInstance.majorLevel = (jobInstance.majorLevel==null)?"":jobInstance.majorLevel
        
        def round = Config.findByConfigKey('round')?.configValue
        jobInstance.round = round
         
        if(session.department==null)
        {
            flash.message = "只有系部角色才能保存招聘信息"
            redirect(controller:"Job",action: "create")
            return
        }
        def departmentInstance  =  Department.get(session.department.id)
        jobInstance.department = departmentInstance
        
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        jobInstance.currentTerm = currentTerm
        if (!jobInstance.save(flush: true)) {
            render(view: "create", model: [jobInstance: jobInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'job.label', default: 'Job'), jobInstance.courseName])
        redirect(controller:"Course",action: "job", id: jobInstance.id)
    }

    def show() {
        def jobInstance = Job.get(params.id)
        if (!jobInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'job.label', default: 'Job'), params.id])
            redirect(action: "list")
            return
        }

        [jobInstance: jobInstance]
    }

    def edit() {
        // def jobInstance = Job.get(params.id)
        def job = new Job(params)
        def jobInstance = Job.find(job)
        if (!jobInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'job.label', default: 'Job'), params.id])
            redirect(action: "list")
            return
        }

        [jobInstance: jobInstance]
    }

    def update() {
        def jobInstance = Job.get(params.id)
        if (!jobInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'job.label', default: 'Job'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (jobInstance.version > version) {
                jobInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                    [message(code: 'job.label', default: 'Job')] as Object[],
                          "Another user has updated this Job while you were editing")
                render(view: "edit", model: [jobInstance: jobInstance])
                return
            }
        }

        jobInstance.properties = params

        if (!jobInstance.save(flush: true)) {
            render(view: "edit", model: [jobInstance: jobInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'job.label', default: 'Job'), jobInstance.id])
        // redirect(action: "show", id: jobInstance.id)
        redirect(controller:"Course",action: "job", id: jobInstance.id)
    }

    def delete() {
        //TODO 判断截至日期
        def deadline = Config.findByConfigKey('teacherForecast')?.configValue
        def sdf = new SimpleDateFormat("yyyy-MM-dd")//格式化时间输出
        def currentDate = sdf.format(new Date())
        if(currentDate>deadline)
        {
            flash.message="当前已经超过截至日期"
            redirect(controller:"Course",action: "job")
            return
        }
        def job = new Job(params)
        def jobInstance = Job.find(job)
       // def jobInstance = Job.get(params.id)
        if (!jobInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'job.label', default: 'Job'), params.id])
            redirect(controller:"Course",action: "job")
            return
        }

        try {
            jobInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'job.label', default: 'Job'), jobInstance.courseName])
            redirect(controller:"Course",action: "job")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = "此招聘信息已经有人申请，暂时无法删除"
            redirect(controller:"Course",action: "job")
        }
    }
}
